//
//  DFPullDownRefreshControl.swift
//  FlyBlog
//
//  Created by FEI on 16/4/17.
//  Copyright © 2016年 FEI. All rights reserved.
//

import UIKit

private let DFPullDownRefreshControlHeight:CGFloat = 60

enum DFPullDownRefreshControlStatus: Int {
    case Normal   //箭头朝下
    case PullDownRefresh  //箭头朝上
    case Refreshing  //正在刷新
}

class DFPullDownRefreshControl: UIView {

    var pullDownRefreshHandler: (() -> ())?

    private var superScrollView: UIScrollView?

    private var status:DFPullDownRefreshControlStatus = DFPullDownRefreshControlStatus.Normal {
        didSet {
            switch status {
            case .Normal:
                DFPrint("normal")
                fhlView.hidden = true
                arrowView.hidden = false
                messageLabel.text = "下拉刷新"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowView.transform = CGAffineTransformIdentity
                })

            case .PullDownRefresh:
                DFPrint("pullDown")
                messageLabel.text = "释放刷新"
                UIView.animateWithDuration(0.25, animations:
                    { () -> Void in
                   self.arrowView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
            })

            case .Refreshing:
                DFPrint("refreshing")
                messageLabel.text = "正在刷新"
                fhlView.hidden = false
                arrowView.hidden = true

                let rotationAnimate = CABasicAnimation(keyPath: "transform.rotation")
                rotationAnimate.toValue = M_PI * 2
                rotationAnimate.repeatCount = MAXFLOAT
                rotationAnimate.duration = 0.5
                rotationAnimate.removedOnCompletion = false

                fhlView.layer.addAnimation(rotationAnimate, forKey: "rotationAnimate")

                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.superScrollView?.contentInset.top += DFPullDownRefreshControlHeight
                })

                pullDownRefreshHandler?()

            }

        }
    }

    func startRefreshing() {
        status = .Refreshing
    }

    func endRefreshing() {
        status = .Normal

        UIView.animateWithDuration(0.25 ,animations :{ () -> Void in
            self.superScrollView?.contentInset.top -= DFPullDownRefreshControlHeight
        })
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError()
    }


    override init(frame: CGRect) {
        let newFrame = CGRect(x: 0, y: -DFPullDownRefreshControlHeight, width: UIScreen.mainScreen().bounds.width, height: DFPullDownRefreshControlHeight)
        super.init(frame: newFrame)

//        backgroundColor = UIColor.brownColor()
        prepareUI()
    }

    private func prepareUI() {
        addSubview(fhlView)
        addSubview(arrowView)
        addSubview(messageLabel)

        fhlView.hidden = true

        fhlView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }

        arrowView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(fhlView)
        }

        messageLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(fhlView.snp_trailing).offset(10)
            make.centerY.equalTo(fhlView)
        }

    }


    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)

        if let scrollView = newSuperview as? UIScrollView {
            superScrollView = scrollView
            superScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        }
    }

    deinit {
        removeObserver(self, forKeyPath: "contentOffset")
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if superScrollView!.dragging {
            if status == .PullDownRefresh && superScrollView?.contentOffset.y > -(superScrollView!.contentInset.top + DFPullDownRefreshControlHeight) {
                DFPrint("切换到normal")
                status = .Normal
            }else if status == .Normal && superScrollView?.contentOffset.y < -(superScrollView!.contentInset.top + DFPullDownRefreshControlHeight) {
                DFPrint("切换到pulldown refresh")
                status = .PullDownRefresh
            }
        }else if status == .PullDownRefresh {
            DFPrint("切换到refresh")
            status = .Refreshing
        }
    }

    //MARK:懒加载
    private lazy var arrowView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

    private lazy var fhlView: UIImageView = UIImageView(image: UIImage(named: "tableview_loading"))

    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.darkGrayColor()
        label.text = "下拉刷新"
        return label
    }()

}
